package com.tanx.cqrs.saga.impl;

import com.tanx.cqrs.event.Event;
import com.tanx.cqrs.saga.SagaHandlerInstance;
import com.tanx.cqrs.saga.SagaInfo;
import com.tanx.cqrs.saga.SagaStoreRepository;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.UUID;

/**
 * mongodb存储类
 */
@Data
public class MongoSagaStoreRepositoryImpl implements SagaStoreRepository {
    private String collectionName;
    @Autowired
    private MongoTemplate mongoTemplate;

    public MongoSagaStoreRepositoryImpl(String collectionName) {
        this.collectionName = collectionName;
    }

    public MongoSagaStoreRepositoryImpl() {
    }

    @Override
    public SagaInfo findSaga(String sagaId, Class<?> sourceClass) {
        Query id = new Query(Criteria.where("_id").is(sagaId));
        return mongoTemplate.findOne(id, MongoSagaInfoImpl.class, collectionName);
    }

    @Override
    public SagaInfo insertSaga(String sagaId, SagaHandlerInstance instance, Event event) {
        SagaInfo info = new MongoSagaInfoImpl(sagaId, instance, event);
        mongoTemplate.save(info, collectionName);
        return info;
    }

    @Override
    public void endSaga(String sagaId, SagaHandlerInstance instance, Event event) {
        Query id = new Query(Criteria.where("_id").is(sagaId));
        Update update = new Update();
        update.addToSet("executeEvents", event).set("status", SagaStatus.FINISH);
        mongoTemplate.findAndModify(id, update, MongoSagaInfoImpl.class, collectionName);
    }

    @Override
    public void updateSagaEventList(String sagaId, Class<?> sourceClass, Event event) {
        Query id = new Query(Criteria.where("_id").is(sagaId));
        Update update = new Update();
        update.addToSet("executeEvents", event);
        mongoTemplate.findAndModify(id, update, MongoSagaInfoImpl.class, collectionName);
    }

    @Override
    public String newUuid() {
        return UUID.randomUUID().toString().replaceAll("-", "");
    }
}
